package vn.co.thn.android.videohot.task;

import java.io.IOException;

import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.api.services.youtube.YouTubeScopes;

import android.content.Context;
import android.os.AsyncTask;

public class VHAuthTask extends AsyncTask<String, Void, Integer> {
	private static String SCOPE = "oauth2:" + YouTubeScopes.YOUTUBE_UPLOAD;
	private static int Auth_Success = 0;
	private static int Auth_Exception = 1;
	private Context mContext;
	private Exception mAuth_Error;
	private AuthCallBack mAuthCallBack;

	public VHAuthTask(Context context, AuthCallBack authCallBack) {
		this.mContext = context;
		this.mAuthCallBack = authCallBack;
	}

	@Override
	protected Integer doInBackground(String... params) {
		try {
			String token = GoogleAuthUtil.getToken(mContext, params[0], SCOPE);
			if (token != null) {
				GoogleAuthUtil.invalidateToken(mContext, token);
				return Auth_Success;
			}
			return Auth_Exception;
		} catch (UserRecoverableAuthException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			mAuth_Error = e;
			return Auth_Exception;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			mAuth_Error = e;
			return Auth_Exception;
		} catch (GoogleAuthException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			mAuth_Error = e;
			return Auth_Exception;
		}
	}

	@Override
	protected void onPostExecute(Integer result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		if (result == Auth_Success) {
			this.mAuthCallBack.AuthSuccess();
		}
		if (result == Auth_Exception) {
			this.mAuthCallBack.AuthError(mAuth_Error);
		}
	}

	public interface AuthCallBack {
		public void AuthSuccess();

		public void AuthError(Exception e);
	}
}
